<template>
    <ContentWrap v-loading="loading">
        <div class="Business_content">
            <h2 class="fonts24 fontw500">企业信息展示</h2>
            <div class="business_menu">
                <el-menu :default-active="state.activeIndex" class="el-menu-demo" mode="horizontal"
                    @select="handleSelect">
                    <el-menu-item index="0">公司信息</el-menu-item>
                    <el-menu-item index="1">邮箱配置</el-menu-item>
                    <!-- <el-menu-item index="2">意见反馈</el-menu-item> -->
                </el-menu>
            </div>
            <el-form ref="ruleFormRef" v-if="state.activeIndex == `0`" :model="state.ruleForm" :rules="rules"
                label-width="120px" class="demo-ruleForm" status-icon>
                <el-form-item label="公司名称" prop="companyName">
                    <el-input v-model="state.ruleForm.companyName" placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="公司Logo" prop="companyLogoId">
                    <UpLoadImage :data="state.upLoadImage" @uploadImageClick="uploadImageClick" />
                </el-form-item>
                <el-form-item label="公司性质" prop="">
                    <el-select v-model="state.ruleForm.companyType" class="m-2" placeholder="请选择公司性质"
                        style="width: 200px;">
                        <el-option v-for="item in state.options1" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="公司规模" prop="">
                    <el-select v-model="state.ruleForm.companySize" class="m-2" placeholder="请选择公司规模"
                        style="width: 200px;">
                        <el-option v-for="item in state.options2" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属行业" prop="">
                    <el-select v-model="state.ruleForm.companyIndustry" class="m-2" placeholder="请选择所属行业"
                        style="width: 200px;">
                        <el-option v-for="item in state.options3" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工作时间" prop="">
                    <el-input v-model="state.ruleForm.workTimeStart" placeholder="请输入工作时间" />
                    <!-- <el-time-picker v-model="state.ruleForm" is-range range-separator="To" start-placeholder="开始时间"
                        end-placeholder="结束时间" /> -->
                </el-form-item>
                <el-form-item label="福利待遇" prop="" class="formitem">
                    <el-select v-model="state.ruleForm.welfareTreatment" multiple collapse-tags placeholder="请选择福利待遇">
                        <el-option v-for="item in state.options9" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="公司地址" prop="">
                    <el-input v-model="state.ruleForm.address" placeholder="请输入公司地址" />
                </el-form-item>
                <el-form-item label="公司简介" prop="">
                    <el-input v-model="state.ruleForm.intro" :autosize="{ minRows: 2 }" type="textarea" rows="4"
                        placeholder="请输入公司简介" />
                </el-form-item>
                <el-form-item label="主营产品与业务" prop="">
                    <el-input v-model="state.ruleForm.mainProducts" :autosize="{ minRows: 2 }" type="textarea" rows="4"
                        placeholder="请输入公司简介" />
                </el-form-item>
                <el-form-item label="公司相册" prop="ossIds">
                    <UpLoadImages v-if="imageBool" :data="state.upLoadImages_" @uploadImageClick="uploadImageClicks_" />
                </el-form-item>
                <el-form-item>
                    <div class="flex jcfe" style="width: 100%;">
                        <el-button type="primary" @click="submitForm(ruleFormRef)" style="width: 100%;">保存</el-button>
                    </div>
                    <div class="flex jcfe" style="width: 100%;margin-top: 20px;" v-if="state.adminBool">
                        <el-button type="primary" link @click="delData()" style="width: 100%;">注销企业</el-button>
                    </div>
                </el-form-item>

            </el-form>
            <el-form ref="ruleFormRef" v-if="state.activeIndex == `1`" :model="state.ruleFormEmail" :rules="rules"
                label-width="120px" class="demo-ruleForm" status-icon>
                <el-form-item label="邮箱地址：" prop="fromMail">
                    <el-input v-model="state.ruleFormEmail.fromMail" placeholder="请输入邮箱地址" />
                </el-form-item>
                <el-form-item label="用户名：" prop="username">
                    <el-input v-model="state.ruleFormEmail.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="密码：" prop="pass">
                    <el-input v-model="state.ruleFormEmail.pass" placeholder="请输入密码" type="password" show-password />
                </el-form-item>
                <el-form-item label="SMTP服务器：" prop="host">
                    <el-input v-model="state.ruleFormEmail.host" placeholder="请输入SMTP服务器" />
                </el-form-item>
                <el-form-item label="端口：" prop="port">
                    <el-input v-model="state.ruleFormEmail.port" placeholder="请输入端口" />
                </el-form-item>
                <el-form-item label="SSL：" prop="sslEnable">
                    <el-switch v-model="state.ruleFormEmail.sslEnable" active-value="1" inactive-value="0" />
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-input v-model="state.ruleFormEmail.remark" placeholder="请输入备注" :autosize="{ minRows: 2 }"
                        type="textarea" />
                </el-form-item>

                <el-form-item>
                    <div class="flex jcfe" style="width: 100%;">
                        <el-button type="primary" @click="submitFormEmail(ruleFormRef)"
                            style="width: 100%;">保存</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <div class="facebooks" @click="open">
                反馈
            </div>
        </div>
        <Dialog v-model="dialogVisible1" title="意见反馈" width="650" style="overflow: hidden;">
            <el-form  ref="ruleFormRef" label-position="top" :model="state.ruleFormL" :rules="rules"
                label-width="120px" class="demo-ruleForm" status-icon>
                <el-form-item label="反馈内容" prop="feedback">
                    <el-input type="textarea" v-model="state.ruleFormL.feedback" placeholder="请输入反馈内容" />
                </el-form-item>
                <el-form-item label="图片" prop="feedbackOssIds">
                    <UpLoadImages  :data="state.upLoadImages_L" @uploadImageClick="uploadImageClicks_L" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitFormL(ruleFormRef)">
                        提交
                    </el-button>
                    <el-button @click="dialogVisible1=false">取消</el-button>
                </el-form-item>
            </el-form>
        </Dialog>
    </ContentWrap>
</template>

<script lang="ts" setup>
import { dictSect } from "@/utils/dictUnit"
import { getTenant, editTenant, getTypeListApi, getTenantMail, editTenantMail, deleteUser ,feedback} from "@/api/business/index"
import UpLoadImage from "@/views/Components/UpLoadImage.vue"
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import type { UploadProps } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { resetRouter } from '@/router'
import { useTagsViewStore } from '@/store/modules/tagsView'
import UpLoadImages from "@/views/Components/UpLoadImages.vue"
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useStorage } from '@/hooks/web/useStorage'
import { useAppStoreWithOut } from '@/store/modules/app'
import { onMounted } from "vue"
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const userInfo = getStorage(appStore.getUserInfo)
const dialogVisible1 = ref(false)
const state = reactive({
    ruleFormL:{} as any,
    activeIndex: "0",
    adminBool: JSON.parse(sessionStorage.getItem("my_Info")).roles[0] == "admin" ? true : false,
    upLoadImage: {
        url: "",
        tip: "注意:建议尺寸：120*120像素图片大小不超过2M，支持jpg、jpeg、png格式",
        actionUrl: "/api/enterprise/oss/upload",
        headers: {
            "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
            "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
        },

    },
    ruleForm: {} as any,
    ruleFormEmail: {
        sslEnable: "1"
    } as any,
    options1: [] as any,
    options2: [] as any,
    options3: [] as any,
    options9: [] as any,//福利待遇
    upLoadImages_: {
        tip: "建议尺寸：最多上传10张，单张图片大小不超过10M，支持jpg、jpeg、png格式",
        urls: [],
        ossIds: "",
        limit: 10,
        size: 10,
        actionUrl: "/api/enterprise/oss/upload",
        headers: {
            "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
            "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
        }
    },
    upLoadImages_L: {
        tip: "建议尺寸：最多上传10张，单张图片大小不超过10M，支持jpg、jpeg、png格式",
        urls: [],
        ossIds: "",
        limit: 10,
        size: 10,
        actionUrl: "/api/enterprise/oss/upload",
        headers: {
            "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
            "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
        }
    },
})
const open=()=>{
    dialogVisible1.value=true
    state.ruleFormL={}
    state.upLoadImages_L.url=[]
}
const uploadImageClick = (value: any) => {
    state.ruleForm.companyLogoId = value
    console.log("单图片上传", state.ruleForm.companyLogoId);
}
const uploadImageClicks_ = (value: any) => {
    state.ruleForm.adPicIds = value
    console.log("多图片上传", state.ruleForm.adPicIds);
}
const uploadImageClicks_L = (value: any) => {
    state.ruleFormL.feedbackOssIds = value
    console.log("多图片上传", state.ruleForm.feedbackOssIds);
}
function urlFun(data) {
    let arrays = [] as any
    data.forEach(element => {
        let obj = {
            response: {
                data: {
                    ossId: element.ossId,
                    url: element.url
                }
            },
            url: element.url
        }
        arrays.push(obj)
    });
    return arrays
}
function urlFuns(data, ids) {
    let array = data
    let arrayIds = ids.split(',')
    let arrays = [] as any
    array.forEach(element => {
        let obj = {
            response: {
                data: {
                    ossId: "",
                    url: element.url
                }
            },
            url: element.url
        }
        arrays.push(obj)
    });
    arrayIds.forEach((element, key) => {
        arrays[key].response.data.ossId = element
    });
    console.log(arrays);
    return arrays


}
const handleSelect = (key: string, keyPath: string[]) => {
    console.log("表头", key, keyPath)
    state.activeIndex = key
}
interface RuleForm {
    companyName: string
    companyLogoId: string
    companyIndustry: string
    companySize: string
    companyType: string
    intro: string
    host: string
    username: string
    pass: string
    port: string
    fromMail: string
    sslEnable: string
    remark: string
    feedback:string
    feedbackOssIds:string
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    feedback: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }],
    feedbackOssIds: [{ required: true, message: '请上传图片', trigger: 'blur' }],
    fromMail: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] },],
    host: [{ required: true, message: '请输入SMTP服务器', trigger: 'blur' }],
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    pass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
    sslEnable: [{ required: true, message: '请输入', trigger: 'blur' }],
    remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
    companyLogoId: [{ required: true, message: '请上传公司logo', trigger: 'blur' }],
    companyName: [
        { required: true, message: '请填写公司名称', trigger: 'blur' },
        { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    ],
    companyIndustry: [
        { required: true, message: '请选择所属行业', trigger: 'blur' }
    ],
    companySize: [
        { required: true, message: '请选择公司规模', trigger: 'blur' }
    ],
    companyType: [
        { required: true, message: '请选择公司性质', trigger: 'blur' }
    ],
    intro: [
        { min: 1, max: 5000, message: '不超过5000个字符', trigger: 'blur' },
    ],

})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            loading.value = true
            state.ruleForm.welfare = stringFun(state.ruleForm.welfareTreatment)
            editTenant(state.ruleForm).then((res: any) => {
                loading.value = false
                ElMessage.success(res.msg)
            }).catch((res: any) => {
                ElMessage.error(res.msg)
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const submitFormL = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            // state.ruleForm.id=""
            feedback(state.ruleFormL).then((res: any) => {
                dialogVisible1.value=false
                ElMessage.success(res.msg)
            }).catch((res: any) => {
                ElMessage.error(res.msg)
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const submitFormEmail = async (formEl: FormInstance | undefined) => {//邮箱
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            loading.value = true
            editTenantMail(state.ruleFormEmail).then((res: any) => {
                loading.value = false
                ElMessage.success(res.msg)
            }).catch((res: any) => {
                ElMessage.error(res.msg)
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const loading = ref(false)
const imageBool = ref(false)
const getTenantApi = async () => {
    imageBool.value = false
    state.options9 = dictSect("welfare_treatment")
    await getTenant().then(res => {
        imageBool.value = true
        console.log("企业信息", res);
        state.ruleForm = res.data
        state.upLoadImage.url = res.data.companyLogoUrl
        state.ruleForm.welfareTreatment = stringFun2(state.ruleForm.welfare)
        state.upLoadImages_.urls = urlFuns(res.data.adPicFiles, res.data.adPicIds)
    }).catch(res => {
        console.log(res);

    })
}
function stringFun(array) {
    let string = ""
    array.forEach(element => {
        if (string == "") {
            string = element
        } else {
            string = string + "," + element
        }

    });
    return string
}
function stringFun2(str) {
    let arr = []
    if (str) {
        arr = str.split(",");
    }
    return arr
}
const getTenantMailApi = async () => {
    await getTenantMail().then(res => {
        console.log("企业邮箱：", res);
        if (res.data) {
            state.ruleFormEmail = res.data
            state.ruleFormEmail.sslEnable = res.data.sslEnable + ''
        }

    }).catch(res => {
        console.log(res);

    })
}
// 字典
const getTypeListApi_ = () => {
    state.options1 = dictSect("company_type")
    state.options2 = dictSect("company_size")
    state.options3 = dictSect("company_industry")
}
getTenantMailApi()
getTenantApi()
getTypeListApi_()

const { clear } = useStorage()
const tagsViewStore = useTagsViewStore()
const { replace } = useRouter()
const delData = () => {
    ElMessageBox.confirm('温馨提示：账号注销后，账号相关信息均会被删除，且不可找回!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        deleteUser().then((res: any) => {
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
            clear()
            tagsViewStore.delAllViews()
            resetRouter() // 重置静态路由表
            replace('/login')
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    text-align: center;
}
</style>
<style lang="less" scoped>
.business_menu {
    // width: 250px;
    margin-bottom: 16px;
    padding: auto;
}

.avatar-uploader .avatar {
    width: 90px;
    height: 90px;
    display: block;
}

.Business_content {
    position: relative;

    .facebooks {
        bottom: 120px;
        right: 80px;
        border-radius: 50%;
        position: fixed;
        height: 60px;
        width: 60px;
        background-color: var(--el-bg-color-overlay);
        box-shadow: var(--el-box-shadow-lighter);
        text-align: center;
        line-height: 40px;
        color: #1989fa;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .el-form-item {
        width: 40%;

        .el-select {
            width: 100%;
        }
    }

    h2 {
        position: relative;
        margin: 0;
        margin-bottom: 36px;

        &::after {
            position: absolute;
            left: -20px;
            top: 2px;
            content: "";
            width: 8px;
            height: 24px;
            background: #2F6CBC;
            border-radius: 0px 4px 4px 0px;
            opacity: 1;
        }
    }
}
</style>